package com.buddies.lottery.data;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.buddies.lottery.App;
import com.buddies.lottery.common.ConfigManager;
import com.buddies.lottery.data.result.ApiResult;
import com.buddies.lottery.exception.ApiException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * Created by xuliang on 2018/2/27.
 */

public class HandleResultHelper {

    /**
     * 对结果进行预处理
     */
    public static final <T> ObservableTransformer<ApiResult<T>, T> handleResult() {
        return new ObservableTransformer<ApiResult<T>, T>() {
            @Override
            public ObservableSource apply(Observable upstream) {
                return upstream.flatMap(new Function<ApiResult<T>, Observable<T>>() {
                    @Override
                    public Observable<T> apply(ApiResult<T> result) {
                        if (result.isResultOk()) {//检查是否掉接口成功了
                            if (!TextUtils.isEmpty(result.renew_token)) {
                                ConfigManager.getInstance().setToken(result.renew_token);
                            }
                            if (result.ts > 0) {
                                App.getInstance().updateDeltaByServerTime(result.ts);
                            }
                            return createData(result.data);//成功，剥取我们要的数据
                        } else {
                            // 根据服务器返回的不同状态码，可以自定义异常
                            return Observable.error(new ApiException(result.err, result.err_msg));//出错就返回服务器错误
                        }
                    }
                });
            }
        };
    }

    /**
     * 创建成功的数据
     */
    private static <T> Observable<T> createData(final T data) {
        return Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<T> subscriber) throws Exception {
                try {
                    subscriber.onNext(data);
                    subscriber.onComplete();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        });
    }
}
